import pygame
from   pygame import Rect

from constants import LEFT,RIGHT,UP,DOWN

class Entity:
  def __init__(self,pos,size,image_set):
    self.rect = Rect((0,0),size)
    
    self.rect.centerx = pos[0]
    self.rect.bottom  = pos[1]
    
    self.image_set = image_set
    
    self.velocity   = [0,0]
    self.collisions = [False,False,False,False]
  
  def move_and_collide(self,solids):
    self.collisions[0] = False
    self.collisions[1] = False
    self.collisions[2] = False
    self.collisions[3] = False
    
    self.rect.left += self.velocity[0]
    
    for block in solids:
      if self.rect.colliderect(block.rect):
        my_r = self.rect
        bl_r = block.rect
        
        if my_r.centerx > bl_r.centerx and my_r.left < bl_r.right:
          my_r.left              = bl_r.right
          self.collisions[LEFT]  = True
        if my_r.centerx < bl_r.centerx and my_r.right > bl_r.left:
          my_r.right             = bl_r.left
          self.collisions[RIGHT] = True
    
    self.rect.top += self.velocity[1]
    
    for block in solids:
      if self.rect.colliderect(block.rect):
        my_r = self.rect
        bl_r = block.rect
        
        if my_r.centery > bl_r.centery and my_r.top < bl_r.bottom:
          my_r.top              = bl_r.bottom
          self.collisions[UP]  = True
        if my_r.centery < bl_r.centery and my_r.bottom > bl_r.top:
          my_r.bottom             = bl_r.top
          self.collisions[DOWN] = True
  
  def update_velocity(self):
    if self.velocity[0] < -35:
      self.velocity[0] = -35
    if self.velocity[0] >  35:
      self.velocity[0] =  35
    
    if self.velocity[1] < -35:
      self.velocity[1] = -35
    if self.velocity[1] >  35:
      self.velocity[1] =  35
    
    if self.collisions[RIGHT] or self.collisions[LEFT]:
      self.velocity[0] = 0
    
    if self.collisions[DOWN] or self.collisions[UP]:
      self.velocity[1] = 0
    
    self.velocity[1] += 1
  
  def get_image(self):
    return self.image_set['Only']
  
  def get_blit_info(self):
    image     = self.get_image()
    blit_rect = image.get_rect()
    
    blit_rect.centerx = self.rect.centerx
    blit_rect.bottom  = self.rect.bottom
    
    return image,blit_rect
  

class Agent(Entity):
  def __init__(self,pos,size,health,speed,image_set,sound_set):
    Entity.__init__(self,pos,size,image_set)
    
    self.sound_set = sound_set
    
    self.health = health
    self.speed  = speed
    
    self.status      = 'Idle'
    self.frame       = 0
    self.frame_timer = 0
    self.left        = False
  
  def update(self,solids):
    self.move_and_collide(solids)
    self.update_velocity()
